package com.qk.management.controller;

import com.qk.common.PageResult;
import com.qk.common.Result;
import com.qk.dto.role.RoleDTO;
import com.qk.entity.Role;
import com.qk.management.service.RoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping(path = "/roles")
@SuppressWarnings("all")
public class RoleController {

    @Autowired
    private RoleService roleService;

    @GetMapping
    public Result getAllRoles() {
        List<Role> roles = roleService.getAllRoles();
        return Result.success(roles);
    }

    @GetMapping("/{id}")
    public Result getRoleById(@PathVariable Integer id) {
        Role role = roleService.getRoleById(id);
        return Result.success(role);
    }

    @PostMapping
    public Result addRole(@RequestBody Role role) {
        try {
            roleService.addRole(role);
            return Result.success();
        } catch (Exception e) {
            log.error("新增角色失败: {}", e.getMessage());
            return Result.error("新增角色失败");
        }
    }

    @PutMapping
    public Result updateRole(@RequestBody Role role) {
        try {
            roleService.updateRole(role);
            return Result.success();
        } catch (Exception e) {
            log.error("修改角色失败: {}", e.getMessage());
            return Result.error("修改角色失败");
        }
    }


    @DeleteMapping("/{id}")
    public Result deleteRole(@PathVariable Integer id) {
        try {
            roleService.deleteRoleById(id);
            return Result.success();
        } catch (Exception e) {
            log.error("删除角色失败: {}", e.getMessage());
            return Result.error("删除角色失败");
        }
    }

    @GetMapping
    public Result page(RoleDTO dto){
        PageResult<Role> result = roleService.page(dto);
        return Result.success(result);
    }
    @GetMapping("/list")
    public Result list(){
        return Result.success(roleService.list());
    }

}